#include "musicServer.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include"stdTcpService.h"
#include<memory>
#include"stdShared.h"
#include<json-c/json.h>
#include<jsoncpp/json/json.h>
#include"stdSqlliteDatebase.h"
musicServer::musicServer(void *arg)
{
    StdTcpSocket* clientSockPtr = reinterpret_cast<StdTcpSocket*>(arg);
    std::shared_ptr<StdTcpSocket> clientSock(clientSockPtr);  
    m_clientInfo=clientSock;

}

musicServer::~musicServer()
{

}

void musicServer::handleRegister(const std::string &info)
{


      std::cout << "Received register info: " << info << std::endl;

        Json::Value root;
        Json::CharReaderBuilder reader;
        /*解析json字符串*/
        std::istringstream s(info);
        Json::parseFromStream(reader,s,&root,nullptr);
        std::string username=root["username"].asString();
        std::string passwd=root["passwd"].asString();
        if(userExist(username)==true)
        {
                
        json_object *jsonObj=json_object_new_object(); 
        json_object_object_add(jsonObj,"type",json_object_new_int(REGISTER));
        json_object_object_add(jsonObj,"username",json_object_new_string("ON_SUCCESS"));
        json_object_object_add(jsonObj,"passwd",json_object_new_string("注册成功"));

        }
        else
        {
            
        
        }

        /*将json对象转换成字符串*/
        const char *jsonStr=json_object_to_json_string(jsonObj);

        m_clientInfo->sendMessage(jsonStr);



     
          



}

void musicServer::handleLoginInfo(const std::string &info)
{
    std::cout<<"Received login info"<<info<<std::endl;
}

bool musicServer::userExist(const std::string &username)
{
    StdDataBase *db=new StdSqliteBase;
    db->connectDB("./test.db");
    const char*sql="select username from COMPANY";
    char **table=NULL;
    int row=0;
    int column=0;
    /*获取数据库的值*/
    sqlite3_get_table(db,sql,&table,&row,&column,NULL);
    result.datas.resize(row,std::vector<std::string>(column));
   for(int i = 1; i <= row; i++) {
       
           if(table[i*column+j]==username)
           {
            return true;
           }
       
   }
   return false; 
}
